<?php

namespace App\Library\Service;

use App\Library\Logic\AuditLogic;
use App\Library\Logic\OpenIdLogic;
use App\Library\Logic\OperateLogLogic;
use App\Library\Logic\ShopImagesLogic;
use App\Library\Logic\ShopUserLogic;
use App\Library\Requests\Base\IdRequest;
use App\Library\Requests\User\UserCompanyAddRequest;
use App\Library\Requests\User\UserEditRequest;
use App\Models\OpenIdModel;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;

class UserService extends BaseService
{
    /**
     * @param ShopUserLogic $logic
     */
    public function __construct(ShopUserLogic $logic)
    {
        $this->logic = $logic;
    }

    public function setAgent(IdRequest $request): JsonResponse
    {
        $item = $this->logic->detail($request->id, ['user_id', 'agent', 'user_type', 'user_delete_flag']);
        if (is_null($item) || $item->user_type !== 2 || $item->user_delete_flag === 1) return fail();
        $item->agent = !$item->agent;
        $item->save();
        $k = 'agent:' . $request->id;
        if ($item->agent) cache([$k => 1]);
        else cache()->forget($k);
        OperateLogLogic::add();
        return success();
    }

    public function auditInfo(): JsonResponse
    {
        $arr = __('audit.auditType');
        $list = AuditLogic::query()->where('user_id', USERID)->whereIn('type', array_keys($arr))->groupBy('type')
            ->pluck(DB::raw('group_concat(distinct status order by created_at desc)'), 'type')->toArray();
        foreach ($arr as $k => $v) {
            if (!isset($list[$k])) {
                $list[$k] = -1;
                continue;
            }
            if (strlen($list[$k]) > 1) $list[$k] = substr($list[$k], 0, 1);
            $list[$k] = (int)$list[$k];
        }
        return success($list);
    }

    /**
     * info
     * @return JsonResponse
     */
    public function info(): JsonResponse
    {
        $user = cacheUser(ShopUserLogic::detail(USERID), 1);
        $user['kefu'] = cache()->has('kf:' . USERID);
        $openInfo = DB::table('open_id')->where('user_id', USERID)->first();
        $user['wx_openid'] = '';
        $data = [];
        if (!empty($openInfo)) {
            $user['wx_openid'] = $openInfo->openid;
            $tokenUrl = sprintf(__('wechat.gz.tokenUrl'), __('wechat.gz.appId'), __('wechat.gz.secret'));
            $tokenInfo = json_decode(file_get_contents($tokenUrl), true);
            if (!empty($tokenInfo)) {
                $url = sprintf(__('wechat.gz.url'), $tokenInfo['access_token'], $openInfo->openid);
                $data = json_decode(file_get_contents($url), true);
            }
        }
        $user['is_gz'] = $data['subscribe'] ?? 0;
        return success($user);
    }

    /**
     * 编辑用户信息
     * @param UserEditRequest $request
     * @return JsonResponse
     * @throws Exception
     */
    public function edit(UserEditRequest $request): JsonResponse
    {
        $array = [
            'userProvince' => null,
            'userCity' => null,
            'userCounty' => null,
        ];
        if (!is_null($request->address)) {
            $addressArr = explode('-', $request->address);
            $array['userProvince'] = $addressArr[0];
            $array['userCity'] = $addressArr[1];
            $array['userCounty'] = $addressArr[2];
        }
        $array['userNickname'] = $request->nickname;
        $array['userNote'] = $request->note;
        $array['userAvatar'] = $request->fileId;
        $this->logic->updateForModel($array, $this->logic->detail(USERID, 'user_id'));
        mq('cacheUser', (string)USERID);
        OperateLogLogic::add();
        return success();
    }

    /**
     * 退出登录
     * @return JsonResponse
     */
    public function logout(): JsonResponse
    {
        forgetCache();
        OperateLogLogic::add();
        return success();
    }

    /**
     * companyAdd
     * @param UserCompanyAddRequest $request
     * @return JsonResponse
     */
    public function companyAdd(UserCompanyAddRequest $request): JsonResponse
    {
        $this->logic->updateByWhere([
            'user_shop_name' => $request->name,
            'userShopBusinessLicenseImgId' => $request->id,
            'userShopStatus' => 2,
        ], 'userId', USERID);
        ShopImagesLogic::updateByWhere(['imgSourceId' => USERID, 'imgIsCover' => 0], [
            'imgId' => $request->id,
            'userMainId' => MAINID,
            'imgSourceType' => 7,
        ]);
        OperateLogLogic::add();
        return success();
    }

    /**
     * companyInfo
     * @return JsonResponse
     */
    public function companyInfo(): JsonResponse
    {
        $user = $this->logic->detail(USERID, ['userShopName', 'userShopBusinessLicenseImgId']);
        $user->img_url = ShopImagesLogic::valueByWhere('imgId', $user->user_shop_business_license_img_id, 'imgUrl');
        return success($user);
    }

    /**
     * cache
     * @param int $id
     * @return JsonResponse
     */
    public function cache(int $id): JsonResponse
    {
        $shopUser = ShopUserLogic::detail($id);
        if (is_null($shopUser)) return fail();
        cacheUser($shopUser);
        return success();
    }
}
